<template>
  <inline-Modal
    :visible="visible"
    :title="pageTitle"
    :showOk="false"
    @cancel="handelCancel()"
  >
    <a-button
      type="primary"
      class="add-btn"
      :loading="loading"
      @click="handelOk()"
      v-if="operateType != 3"
    >
      确定
    </a-button>
    <div class="add-page-container" ref="content">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :hideRequiredMark="isDisabled"
      >
        <div class="sub-title">基本信息</div>
        <div class="base-container">
          <a-row :gutter="50">
            <a-col :span="8">
              <a-form-model-item label="月份" prop="monthData">
                <a-month-picker
                  :disabledDate="disabledDate"
                  style="width:100%"
                  placeholder="请选择月份"
                  format="YYYY-MM"
                  valueFormat="YYYY-MM"
                  v-model="form.monthData"
                  @change="changeMonth($event)"
                  :disabled="operateType == 1 ? false : true"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="年度累计投资"
                prop="yearCompleteInvestment"
              >
                <a-input
                  v-model="form.yearCompleteInvestment"
                  disabled
                ></a-input>
                <span class="page-unit">万元</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="年度计划投资" prop="yearPlanInvestment">
                <a-input v-model="form.yearPlanInvestment" disabled></a-input>
                <span class="page-unit">万元</span>
              </a-form-model-item>
            </a-col>
          </a-row>
        </div>
        <a-divider />
        <div class="sub-title">上月交办事项</div>
        <div class="card-list">
          <div
            class="card-item"
            v-for="(item, index) in form.childData"
            :key="index"
          >
            <div class="card-header">
              交办事项{{ index + 1 }}
              <div
                class="delete-icon"
                @click="handleDel(index)"
                v-if="!isDisabled"
              >
                <a-icon type="close" />
              </div>
            </div>
            <div class="card-body">
              <a-row :gutter="50">
                <a-col :span="12">
                  <a-form-model-item
                    label="交办单位"
                    :prop="'childData.' + index + '.assigningUnits'"
                    :rules="{
                      required: true,
                      message: '请选择交办单位',
                    }"
                  >
                    <!-- <a-select
                      mode="multiple"
                      showSearch
                      :filter-option="filterOption"
                      v-model="item.assigningUnits"
                      placeholder="请选择"
                      :disabled="isDisabled"
                    >
                      <a-select-option
                        :value="v.dicItemCode"
                        v-for="v in dictSoucre"
                        :key="v.uuid"
                      >
                        {{ v.dicItemName }}
                      </a-select-option>
                    </a-select> -->
                    <a-tree-select
                      :disabled="isDisabled"
                      v-model="item.assigningUnits"
                      style="width: 100%"
                      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                      placeholder="请选择"
                      multiple
                      tree-default-expand-all
                      :replaceFields="{
                        children: 'children',
                        title: 'orgName',
                        key: 'id',
                        value: 'uuid',
                      }"
                      :tree-data="treeData"
                    >
                    </a-tree-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="交办完成单位"
                    :prop="'childData.' + index + '.assigningCompleteUnits'"
                    :rules="{
                      required: true,
                      message: '请选择交办完成单位',
                    }"
                  >
                    <!-- <a-select
                      mode="multiple"
                      showSearch
                      placeholder="请选择"
                      v-model="item.assigningCompleteUnits"
                      :filter-option="filterOption"
                      :disabled="isDisabled"
                    >
                      <a-select-option
                        :value="v.dicItemCode"
                        v-for="v in dictSoucre"
                        :key="v.uuid"
                      >
                        {{ v.dicItemName }}
                      </a-select-option>
                    </a-select> -->
                    <a-tree-select
                      :disabled="isDisabled"
                      v-model="item.assigningCompleteUnits"
                      style="width: 100%"
                      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                      placeholder="请选择"
                      multiple
                      tree-default-expand-all
                      :replaceFields="{
                        children: 'children',
                        title: 'orgName',
                        key: 'id',
                        value: 'uuid',
                      }"
                      :tree-data="treeData"
                    >
                    </a-tree-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-form-model-item label="配合单位">
                <!-- <a-select
                  mode="multiple"
                  showSearch
                  :filter-option="filterOption"
                  v-model="item.cooperateUnits"
                  placeholder="请选择"
                  :disabled="isDisabled"
                >
                  <a-select-option
                    :value="v.dicItemCode"
                    v-for="v in dictSoucre"
                    :key="v.uuid"
                  >
                    {{ v.dicItemName }}
                  </a-select-option>
                </a-select> -->
                <a-tree-select
                  :disabled="isDisabled"
                  v-model="item.cooperateUnits"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="请选择"
                  multiple
                  tree-default-expand-all
                  :replaceFields="{
                    children: 'children',
                    title: 'orgName',
                    key: 'id',
                    value: 'uuid',
                  }"
                  :tree-data="treeData"
                >
                </a-tree-select>
              </a-form-model-item>
              <a-form-model-item
                label="交办事项"
                :prop="'childData.' + index + '.tasks'"
                :rules="{
                  required: true,
                  message: '请输入交办事项',
                }"
              >
                <a-input
                  type="textarea"
                  :rows="3"
                  placeholder="请输入"
                  v-model="item.tasks"
                  :disabled="isDisabled"
                ></a-input>
              </a-form-model-item>
            </div>
          </div>
          <div class="add-plus" v-if="!isDisabled">
            <span @click="handleAdd()">
              <a-icon type="plus" />添加交办事项
            </span>
          </div>
        </div>
      </a-form-model>
    </div>
  </inline-Modal>
</template>

<script>
import { getAllProListByQX, getDicItemByCode } from "@/api/common.js";
import {
  glyMeetingSaveOrUpdate,
  getGLYDisabledMonth,
  getGLYDetailByMonth,
} from "@/api/safetyManage";
export default {
  props: {
    visible: {
      type: Boolean,
      required: false,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
    operateType: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      loading: false,
      pageTitle: "",
      isDisabled: false,
      //
      form: {
        //月份
        monthData: "",
        //年度累计
        yearCompleteInvestment: "",
        //年度计划
        yearPlanInvestment: "",
        //上月交办事项
        childData: [],
      },
      rules: {
        monthData: [
          {
            required: true,
            message: "请选择月份",
          },
        ],
      },
      //禁用日期
      disabledMonths: [],
      //字典集合
      dictSoucre: [],
      //
      treeData: [],
    };
  },
  computed: {},
  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    //查询数据
    async getData() {
      //获取当前年份
      await this.checkName();
      //
      await this.getMonthData();
      this.treeData = await this.getTreeSelectData();
      //字典下拉框
      //   this.dictSoucre = await this.getDicCodeData("affiliatedUnit");
      //编辑
      let { operateType, parameter } = this;
      if (operateType != 1) {
        this.getDetail(parameter.monthData);
      }
    },

    checkName() {
      let { operateType } = this;
      switch (Number(operateType)) {
        case 1:
          this.pageTitle = "新增";
          this.isDisabled = false;
          break;
        case 2:
          this.pageTitle = "编辑";
          this.isDisabled = false;
          break;
        case 3:
          this.pageTitle = "查看";
          this.isDisabled = true;
          break;

        default:
          break;
      }
    },
    disabledDate(current) {
      if (!current) {
        return false;
      }
      const yearMonth = current.format("YYYY-MM");
      return this.disabledMonths.includes(yearMonth);
    },
    //查询月份
    getMonthData() {
      return new Promise((resolve, reject) => {
        getGLYDisabledMonth({})
          .then((res) => {
            this.disabledMonths = res?.data ?? [];
            resolve();
          })
          .catch((_) => {
            this.disabledMonths = [];
            reject();
          });
      });
    },
    changeMonth(ev) {
      this.getDetail(ev);
    },
    //查询字典表
    getDicCodeData(dicCode = "") {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: dicCode })
          .then((res) => {
            let { data } = res;
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },
    //查询交办单位
    getTreeSelectData() {
      return new Promise((resolve, reject) => {
        this.$post("/mdata/organization/getTreeSysOrganizationByOrg", {})
          .then((res) => {
            let { data } = res;
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    //详情
    getDetail(month) {
      if (!month) {
        this.form.yearCompleteInvestment = "";
        this.form.yearPlanInvestment = "";
        return;
      }
      return new Promise((resolve, reject) => {
        getGLYDetailByMonth({ monthData: month })
          .then((res) => {
            let { data } = res;
            this.form.yearCompleteInvestment = data.yearCompleteInvestment;
            this.form.yearPlanInvestment = data.yearPlanInvestment;
            //编辑、详情
            if (this.operateType != 1) {
              this.form.monthData = data.monthData;
              this.form.childData = [];
              (data?.childData ?? []).forEach((v) => {
                let {
                  assigningCompleteUnits,
                  assigningUnits,
                  cooperateUnits,
                  tasks,
                  uuid,
                } = v;
                this.form.childData.push({
                  uuid,
                  assigningCompleteUnits: assigningCompleteUnits
                    ? assigningCompleteUnits.split(",")
                    : [],
                  assigningUnits: assigningUnits
                    ? assigningUnits.split(",")
                    : [],
                  cooperateUnits: cooperateUnits
                    ? cooperateUnits.split(",")
                    : [],
                  tasks,
                });
              });
            }
            resolve();
          })
          .catch((_) => {
            reject();
          });
      });
    },
    //新增
    handleAdd() {
      this.form.childData.push({
        assigningUnits: [],
        assigningCompleteUnits: [],
        cooperateUnits: [],
        tasks: "",
        uuid: "",
      });
    },
    //删除
    handleDel(index) {
      this.form.childData.splice(index, 1);
    },

    handelOk() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          let { form, operateType } = this;
          let formJson = {
            //月份
            monthData: form.monthData,
            //年度累计
            yearCompleteInvestment: form.yearCompleteInvestment,
            //年度计划
            yearPlanInvestment: form.yearPlanInvestment,
            //上月交办事项
            childData: [],
            //保存类型 A新增；U编辑
            saveType: operateType == 1 ? "A" : "U",
          };
          form.childData.forEach((v) => {
            let {
              assigningCompleteUnits,
              assigningUnits,
              cooperateUnits,
              tasks,
              uuid,
            } = v;
            formJson.childData.push({
              uuid,
              assigningCompleteUnits: assigningCompleteUnits.toString(),
              assigningUnits: assigningUnits.toString(),
              cooperateUnits: cooperateUnits.toString(),
              tasks,
            });
          });
          glyMeetingSaveOrUpdate(formJson)
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("操作成功", 1.5);
                this.handelCancel();
              } else {
                this.$message.error(res?.message ?? "操作失败");
              }
            })
            .catch((_) => {})
            .finally((_) => {
              this.loading = false;
            });
        }
      });
    },

    handelCancel() {
      this.$parent.getTableData();
      this.$emit("update:visible", false);
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
.add-btn {
  position: absolute;
  top: 10px;
  right: 90px;
}
.add-page-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: auto;
  padding: 0 20px;
  /deep/.ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 102px;
      white-space: pre-wrap;
      display: flex;
      justify-content: flex-end;
      line-height: 20px;
      margin-right: 2px;
      align-items: center;
      height: 36px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
    }
  }
  /deep/.ant-divider {
    margin: 10px 0;
  }
  /deep/.ant-select-disabled
    .ant-select-selection--multiple
    .ant-select-selection__choice {
    background-color: #fafafa !important;
    color: #000000 !important;
  }

  .sub-title {
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: 400;
    font-size: 16px;
    color: #111111;
    letter-spacing: 1px;
  }
  .base-container {
    padding: 0 60px 0 0;
    .page-unit {
      position: absolute;
      right: -34px;
    }
  }
  .card-list {
    padding: 0 60px 0 0;
    .card-item {
      border-radius: 6px 6px 6px 6px;
      box-shadow: 0px 0px 3px 2px rgba(51, 51, 51, 0.14);
      margin: 16px 0;
      .card-header {
        padding: 16px 24px;
        box-sizing: border-box;
        font-family: Microsoft YaHei, Microsoft YaHei;
        font-weight: 400;
        font-size: 16px;
        color: #666666;
        letter-spacing: 1px;
        border-bottom: 1px solid #d9d9d9;
        position: relative;
        .delete-icon {
          cursor: pointer;
          width: 40px;
          height: 32px;
          border-radius: 0px 6px 0px 50px;
          background: rgba(255, 45, 45, 0.2);
          position: absolute;
          top: 0;
          right: 0;

          /deep/.anticon-close {
            position: absolute;
            top: 50%;
            left: 60%;
            transform: translate(-50%, -50%);
            color: #ff2d2d;
          }
        }
      }
      .card-body {
        padding: 10px 20px;
        box-sizing: border-box;
        /deep/.ant-form-item {
          .ant-form-item-label {
            width: 72px;
          }
        }
      }
      &:last-of-type {
        margin-bottom: 0;
      }
    }
    .add-plus {
      margin-top: 16px;
      font-family: Microsoft YaHei, Microsoft YaHei;
      font-weight: 400;
      font-size: 16px;
      color: #1677ff;
      letter-spacing: 1px;
      span {
        cursor: pointer;
      }
    }
  }
}
</style>
